package com.aimei.www.modules.ss.controller;

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiah
 * @time 2018-4-11
 * 自定义错误页面和错误json，所有的请求异常都会被捕获
 */
@Controller
public class BasicErrorController implements ErrorController {

       /*定义错误新的请求路径*/
       private final  String ERROR_PATH = "/error";


       @Override
       public String getErrorPath() {
              return ERROR_PATH;
       }


       @RequestMapping(ERROR_PATH)
       @ResponseBody
       /**错误统一处理,返回错误数据，以json类型展示*/
       public Map errorForJson(HttpServletRequest rq, HttpServletResponse rs) {
              Object stateCode = rq.getAttribute("state_code");
              Enumeration<String> ss = rq.getAttributeNames();
              Map map = new HashMap();
              map.put("code", 1);
              map.put("message", "发生了错误返回json类型数据");
              return map;
       }

       @RequestMapping(value = ERROR_PATH, produces = "text/html")
       /**错误统一处理，返回到指定的页面*/
       public String errorForHtml() {
              /*redirect*/
              return "/myError.html";
       }


       @RequestMapping("/ss")
       @ResponseBody
       /**返回给页面一个/myError.html的字符串，页面请求成功*/
       public String ss() {
              return "/myError.html";
       }


       @RequestMapping("/model")
       /**带着模型返回到指定页面*/
       /*只要是返回的ModelAndView类型，无论用@Controller还是@Controller修饰，返回的都是定位的地址*/
       public ModelAndView model() {
              /*redirect*/
              ModelAndView model = new ModelAndView();
              Map map = new HashMap();
              map.put("code", 11);
              map.put("message", "发生了什么");
              model.addObject(map);
              /*如果不指定viewname，将默认定位到@RequestMapping修饰的页面，本例转到model对应的页面*/
              model.setViewName("good.html");
              return model;
       }
}
